"""
发布器管理器
"""

from typing import Dict, List, Any, Optional
import asyncio

from .base import BasePublisher
from .weibo_publisher import WeiboPublisher
from .twitter_publisher import TwitterPublisher
from .wechat_publisher import WeChatPublisher
from ..core.logger import app_logger


class PublisherManager:
    """发布器管理器"""
    
    def __init__(self):
        self.publishers: Dict[str, BasePublisher] = {}
        self._initialize_publishers()
    
    def _initialize_publishers(self):
        """初始化所有发布器"""
        
        publishers = {
            "weibo": WeiboPublisher(),
            "twitter": TwitterPublisher(),
            "wechat": WeChatPublisher()
        }
        
        for platform, publisher in publishers.items():
            try:
                self.publishers[platform] = publisher
                status = "配置完整" if publisher.is_configured else "模拟模式"
                app_logger.info(f"发布器 {platform} 初始化成功 ({status})")
            except Exception as e:
                app_logger.error(f"发布器 {platform} 初始化失败: {e}")
    
    def get_publisher(self, platform: str) -> Optional[BasePublisher]:
        """获取指定平台的发布器"""
        return self.publishers.get(platform)
    
    def get_available_platforms(self) -> List[str]:
        """获取可用的平台列表"""
        return list(self.publishers.keys())
    
    def get_configured_platforms(self) -> List[str]:
        """获取已配置的平台列表"""
        return [
            platform for platform, publisher in self.publishers.items()
            if publisher.is_configured
        ]
    
    async def publish_to_platform(self, platform: str, content: str, **kwargs) -> Dict[str, Any]:
        """发布内容到指定平台"""
        
        publisher = self.get_publisher(platform)
        if not publisher:
            return {
                "success": False,
                "platform": platform,
                "error": "不支持的平台"
            }
        
        try:
            result = await publisher.publish(content, **kwargs)
            return result
        except Exception as e:
            app_logger.error(f"发布到 {platform} 失败: {e}")
            return {
                "success": False,
                "platform": platform,
                "error": str(e)
            }
    
    async def publish_to_multiple_platforms(
        self, 
        platforms: List[str], 
        content: str, 
        **kwargs
    ) -> Dict[str, Any]:
        """发布内容到多个平台"""
        
        if not platforms:
            platforms = self.get_available_platforms()
        
        # 并发发布到所有平台
        tasks = []
        for platform in platforms:
            if platform in self.publishers:
                task = self.publish_to_platform(platform, content, **kwargs)
                tasks.append((platform, task))
        
        if not tasks:
            return {
                "success": False,
                "error": "没有可用的发布平台"
            }
        
        # 等待所有发布任务完成
        results = {}
        for platform, task in tasks:
            try:
                result = await task
                results[platform] = result
            except Exception as e:
                results[platform] = {
                    "success": False,
                    "platform": platform,
                    "error": str(e)
                }
        
        # 统计发布结果
        total_platforms = len(results)
        successful_platforms = sum(1 for r in results.values() if r.get("success", False))
        
        return {
            "success": successful_platforms > 0,
            "total_platforms": total_platforms,
            "successful_platforms": successful_platforms,
            "failed_platforms": total_platforms - successful_platforms,
            "results": results
        }
    
    async def delete_from_platform(self, platform: str, post_id: str) -> bool:
        """从指定平台删除内容"""
        
        publisher = self.get_publisher(platform)
        if not publisher:
            app_logger.error(f"不支持的平台: {platform}")
            return False
        
        try:
            return await publisher.delete_post(post_id)
        except Exception as e:
            app_logger.error(f"从 {platform} 删除内容失败: {e}")
            return False
    
    async def get_post_status_from_platform(
        self, 
        platform: str, 
        post_id: str
    ) -> Dict[str, Any]:
        """获取指定平台的内容状态"""
        
        publisher = self.get_publisher(platform)
        if not publisher:
            return {
                "exists": False,
                "status": "error",
                "error": "不支持的平台"
            }
        
        try:
            return await publisher.get_post_status(post_id)
        except Exception as e:
            app_logger.error(f"获取 {platform} 内容状态失败: {e}")
            return {
                "exists": False,
                "status": "error",
                "error": str(e)
            }
    
    async def test_all_connections(self) -> Dict[str, bool]:
        """测试所有平台的连接状态"""
        
        results = {}
        
        # 并发测试所有平台连接
        tasks = []
        for platform, publisher in self.publishers.items():
            task = publisher.test_connection()
            tasks.append((platform, task))
        
        for platform, task in tasks:
            try:
                result = await task
                results[platform] = result
                status = "✅" if result else "❌"
                app_logger.info(f"{status} {platform} 连接测试: {'成功' if result else '失败'}")
            except Exception as e:
                results[platform] = False
                app_logger.error(f"❌ {platform} 连接测试异常: {e}")
        
        return results
    
    def get_platform_info(self) -> List[Dict[str, Any]]:
        """获取所有平台的信息"""
        
        platform_info = []
        
        for platform, publisher in self.publishers.items():
            info = {
                "platform": platform,
                "name": publisher.get_platform_name(),
                "configured": publisher.is_configured,
                "status": "ready" if publisher.is_configured else "mock"
            }
            platform_info.append(info)
        
        return platform_info


# 全局发布器管理器实例
publisher_manager = PublisherManager()